<template>
  <div class="set_container">
    <div class="meet_operate">
      <!-- 观众模式,最低权限显示 -->
      <div class="set-list isMinimum" v-if="roomInfo.status != ROOM_STATUS.not_started && isMinimum">
        <div class="set-box" v-for="(item, index) in minimumList" :key="index" @click="minimumClick(item)">
          <div class="icon_box">
            <img class="icon" :src="item.img" />
          </div>
          <span>{{ item.name }}</span>
        </div>
      </div>
      <!-- 观众模式下,互动参会模式 -->
      <div class="set-list isInteraction" v-if="roomInfo.status != ROOM_STATUS.not_started && isInteraction">
        <div class="set-box" :class="item.class" v-for="(item, index) in interactionList" :key="index" @click="InteractionClick(item)">
          <div class="icon_box">
            <img class="icon" :src="!item.active ? item.img : item.Aimg" />
          </div>
          <span>{{ item.active ? item.Aname :item.name }}</span>
        </div>
      </div>
      <!-- 观众模式下,连麦模式参会 -->
      <div class="set-list isConnectAudio" v-if="roomInfo.status != ROOM_STATUS.not_started && isConnectAudio">
        <div class="set-box" :class="item.class" v-for="(item, index) in connectAudioList" :key="index" @click="connectAudioClick(item)">
          <div class="icon_box">
            <img class="icon" :src="!item.active ? item.img : item.Aimg" />
          </div>
          <span>{{ item.active ? item.Aname :item.name }}</span>
        </div>
      </div>
      <!-- 讲者模式下 -->
      <div class="set-list isConnectAudio" v-if="roomInfo.status != ROOM_STATUS.not_started && isLecturer">
        <div class="set-box" :class="item.class" v-for="(item, index) in lecturerList" :key="index" @click="lecturerListClick(item)">
          <div class="icon_box">
            <img class="icon" :src="!item.active ? item.img : item.Aimg" />
          </div>
          <span>{{ item.active ? item.Aname :item.name }}</span>
        </div>
      </div>

      <!-- 主持人模式下的按钮显示 -->
      <div class="set-list" v-if="roomInfo.status != ROOM_STATUS.not_started &&userInfo.userType == USER_TYPE.master">
        <div class="set-box" v-for="(item, index) in setList" :key="index" @click="setClick(item, index)" :class="item.class">
          <div class="icon_box">
            <layout :layoutIndex.sync="layoutIndex" :layoutType="layoutType" @hideLayout="hideLayout" v-if="item.class == 'layout' && showLayout && layoutType == 'change'"></layout>
            <img class="icon" :src="!item.active ? item.icon : item.Aicon" />
            <img v-if="item.class == 'layout'" src="@/assets/img/trtc/icon-voice.png" class="play_icon" alt />
            <div v-if="item.class == 'member'" class="number">10</div>
          </div>
          <span>{{ item.active ? item.name : item.Aname }}</span>
        </div>
      </div>
    </div>
    <div class="meet_info">
      <div class="meet_number" @click="showManagingMembersPopup(3)">
        <img src="@/assets/img/trtc/icon-personnel.png" alt />
        <div>{{ info.member }}</div>
      </div>
      <div class="line"></div>
      <div class="meet_time">
        <img src="@/assets/img/trtc/icon-time.png" alt />
        <div>{{ info.time }}</div>
      </div>
      <!-- 主持人显示的 -->
      <div v-if="userInfo.userType == USER_TYPE.master">
        <div class="meet_end button" v-if="
            roomInfo.status == ROOM_STATUS.conduct ||
            roomInfo.status == ROOM_STATUS.suspend
          ">
          结束会议
        </div>
        <div v-else class="meet_start button" @click="showLayoutFn">
          开始会议
        </div>
      </div>
      <!-- 其他用户显示的 -->
      <div v-else>
        <div class="meet_end button" v-if="
            roomInfo.status == ROOM_STATUS.conduct ||
            roomInfo.status == ROOM_STATUS.suspend
          ">
          离开会议
        </div>
      </div>
    </div>

    <layout :layoutIndex.sync="layoutIndex" :layoutType="layoutType" @hideLayout="hideLayout" @startMeeting="startMeeting" v-if="showLayout && layoutType == 'start'"></layout>
  </div>
</template>

<script>
import unmuted from "@/assets/img/trtc/icon-mute.png";
import muted from "@/assets/img/trtc/icon-dismute.png";
import video from "@/assets/img/trtc/icon-startvideo.png";
import unvideo from "@/assets/img/trtc/icon-stopvideo.png";
import member from "@/assets/img/trtc/icon-manage.png";
import share from "@/assets/img/trtc/icon-share.png";
import screenshot from "@/assets/img/trtc/icon-screenshot.png";
import layout001 from "@/assets/img/layout/pic-lay01-selected.png";
import layout from "./component/layout";
import { mapGetters } from "vuex";
import { ROOM_STATUS, USER_TYPE } from "../../../util/constants";

import UserAPI from "@/api/user";
import RoomAPI from "@/api/room";
export default {
  props: {
    isVideo: Boolean,
    isAudio: Boolean,
  },
  components: {
    layout,
  },
  data() {
    return {
      setList: [
        {
          name: "静音",
          Aname: "静音",
          class: "audio",
          icon: muted,
          Aicon: unmuted,
          active: true,
        },
        {
          name: "开启视频",
          Aname: "停止视频",
          class: "video",
          icon: video,
          Aicon: unvideo,
          active: false,
        },
        {
          name: "管理成员",
          Aname: "管理成员",
          class: "member",
          icon: member,
          Aicon: member,
          active: false,
        },
        {
          name: "合规截图",
          Aname: "合规截图",
          class: "screenshot",
          icon: screenshot,
          Aicon: screenshot,
          active: false,
        },
        {
          name: "导播布局",
          Aname: "导播布局",
          class: "layout",
          icon: layout001,
        },
      ],
      minimumList: [
        {
          name: "互动参会",
          img: require("@/assets/img/trtc/icon-interacte.png"),
        },
        {
          name: "浏览资料",
          img: require("@/assets/img/trtc/icon-ppt.png"),
        },
        {
          name: "开启投屏",
          img: require("@/assets/img/trtc/icon-throw.png"),
        },
      ],
      interactionList: [

        {
          name: "切回观看",
          img: require("@/assets/img/trtc/icon-watch.png"),
        },
        {
          name: "申请连麦",
          img: muted,
        },
        {
          class: 'video',
          name: "停止视频",
          Aname: "开启视频",
          active: false,
          img: unvideo,
          Aimg: video
        },
        {
          name: "开启投屏",
          img: require("@/assets/img/trtc/icon-throw.png"),
        },
      ],
      connectAudioList: [
        {
          name: "切回观看",
          img: require("@/assets/img/trtc/icon-watch.png"),
        },
        {
          class: 'audio',
          name: "静音",
          Aname: "解除静音",
          active: false,
          img: muted,
          Aimg: unmuted
        },
        {
          class: 'video',
          name: "停止视频",
          Aname: "开启视频",
          active: false,
          img: unvideo,
          Aimg: video
        },
        {
          name: "开启投屏",
          img: require("@/assets/img/trtc/icon-throw.png"),
        },
        {
          name: "结束互动",
          img: require("@/assets/img/trtc/icon-endinteract.png"),
        },
      ],
      lecturerList: [
        {
          class: 'audio',
          name: "静音",
          Aname: "解除静音",
          active: false,
          img: muted,
          Aimg: unmuted
        },
        {
          class: 'video',
          name: "停止视频",
          Aname: "开启视频",
          active: false,
          img: unvideo,
          Aimg: video
        },
        {
          name: "开启投屏",
          img: require("@/assets/img/trtc/icon-throw.png"),
        },
      ],
      info: {
        member: 212,
        time: "00:00:00",
      },
      showLayout: false,
      layoutType: "",
      ROOM_STATUS,
      USER_TYPE,
      layoutIndex: 1,
    };
  },
  computed: {
    // 获取当前会议状态
    ...mapGetters(["roomInfo", "userInfo"]),
    // 观看模式,最低用户权限
    isMinimum() {
      if (this.userInfo.userType == USER_TYPE.audience) {
        let isMasterSpeech = this.userInfo.isMasterSpeech; //是否是主讲
        let connectSpeechStatus = this.userInfo.connectSpeechStatus; //连麦状态
        let isInteraction = this.userInfo.isInteraction; //是否是互动
        if (!isMasterSpeech && connectSpeechStatus == 1 && !isInteraction) {
          return true;
        }
      } else {
        return false;
      }
      return false;
    },
    // 观众角色,并且开启互动,但没有连麦
    isInteraction() {
      if (this.userInfo.userType == USER_TYPE.audience && this.userInfo.isInteraction && this.userInfo.connectSpeechStatus != 3) {
        return true;
      } else {
        return false;
      }
    },
    // 观众角色,开启连麦中
    isConnectAudio() {
      if (this.userInfo.userType == USER_TYPE.audience && this.userInfo.connectSpeechStatus == 3) {
        // 判断是否是主讲,如果是主讲则增加 归还主讲 按钮
        return true;
      } else {
        return false;
      }
    },
    // 是否是讲者
    isLecturer() {
      if (this.userInfo.userType == USER_TYPE.lecturer) {
        // 判断是否是主讲,显示申请主讲和归还主讲的按钮
        if (this.userInfo.isMasterSpeech) {
          this.lecturerList[3] = ({ name: '归还主讲', img: require("@/assets/img/trtc/icon-give-keynote.png") })
        } else {
          this.lecturerList[3] = ({ name: '申请主讲', img: require("@/assets/img/trtc/icon-keynote.png") })
        }
        return true;
      } else {
        return false;
      }
    },
  },
  watch: {
    isVideo: {
      handler(newVal, oldVal) {
        this.$set(this.setList[1], "active", newVal);
      },
      immediate: true,
    },
    isAudio: {
      handler(newVal, oldVal) {
        this.$set(this.setList[0], "active", newVal);
      },
      immediate: true,
    },
  },
  mounted() {
    this.setList.splice(2, 0, {
      name: "共享桌面",
      Aname: "共享桌面",
      class: "share",
      icon: share,
      Aicon: share,
      active: false,
    });
  },
  methods: {
    // 开始会议
    async startMeeting() {
      let roomId = this.roomInfo.trtcRoomId;
      let status = ROOM_STATUS.conduct;
      let res = await RoomAPI.UpdateRoomStatus({ roomId, status });
      if (res && res.data && res.status == 200 && res.data.trtcRoomId) {
        // 更改房间会议信息
        this.$store.dispatch("setRoomInfo", res.data);
        this.$message({
          type: "success",
          message: "会议开始",
        });
        let data = {
          data: {
            status: this.ROOM_STATUS.conduct,
          },
          description: "tempo",
          extension: "ROOMControl",
        };
        data.data = JSON.stringify(data.data);
        // 向其他用户发送会议开始
        this.$store.dispatch("setIMFn", {
          name: "createCustomMessage",
          data: {
            groupID: this.groupID,
            data,
          },
        });
        // 开启trtc和白板
        this.$store.dispatch("setTRTCFn", {
          name: "IMroomControl",
          data: data,
        });
        return;
      }
      this.$message({
        type: "error",
        message: "会议开始失败",
      });
    },
    showLayoutFn() {
      this.layoutType = "start"; //开始
      this.showLayout = true;
    },
    hideLayout(url) {
      this.showLayout = false;
      let type = "layout";
      if (!url) return;
      let index = this.setList.findIndex((item) => {
        return item.class == type;
      });
      this.setList[index].icon = url;
    },
    showManagingMembersPopup() {
      this.$emit("showManagingMembersPopup", 3);
    },
    setClick(item, index) {
      // 操控声音
      if (item.class == "audio") {
        item.active = !item.active;
        this.$emit("muteAudio", item.active);
      }
      // 操控视频
      if (item.class == "video") {
        item.active = !item.active;
        this.$emit("muteVideo", item.active);
      }
      // 共享桌面
      if (item.class == "share") {
        this.$emit("screenSharing");
      }
      // 管理成员
      if (item.class == "member") {
        // 显示管理成员的弹窗
        this.$emit("showManagingMembersPopup", 1);
      }
      // 导播布局
      if (item.class == "layout") {
        this.showLayout = !this.showLayout;
        this.layoutType = "change"; //改变
        // this.$emit("showManagingMembersPopup", 2);
      }
    },
    // 互动参会,浏览资料等等
    minimumClick(item) {
      if (item.name == "互动参会") {
        this.$confirm("即将进入互动参会模式，确认是否继续", "切换模式", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            console.log("切换到互动模式");
            let res = await UserAPI.updateUserInfo({
              userId: this.userInfo.userId,
              userInfo: { isInteraction: true, video: true },
            });
            if (res && res.status == 200 && res.data.userId == this.userInfo.userId) {
              this.$message({ type: "success", message: "互动参会成功" });
              console.log(res.data);
              let data = {
                data: res.data,
                description: "updateUser",
                extension: "TRTCControl",
              };
              data.data = JSON.stringify(data.data);
              // 向其他用户广播最新用户信息
              this.$store.dispatch("setIMFn", { name: "createCustomMessage", data: { data } });
              // 用户变为互动用户时,修改stote
              this.$store.dispatch("setUserInfo", res.data);
              // 用户变为互动用户时,需要执行trtc中的init方法
              this.$store.dispatch("setTRTCFn", { name: "init" });

            } else {
              this.$message({ type: "error", message: "互动参会失败", });
            }
          })
          .catch(() => {
            console.log("取消切换互动模式");
          });
      }
    },
    // 切换观看模式,申请连麦,停止视频,开启投屏等等
    async InteractionClick(item, index) {
      // 切回观看,自动断开连麦,和主讲模式
      if (item.name == '切回观看') {
        this.backWatch(item);
      }
      // 停止视频
      if (item.class == 'video') {
        item.active = !item.active;
        this.$emit("muteVideo", item.active);
      }
      // 申请连麦
      if (item.name == '申请连麦') {
        let res = await UserAPI.updateUserInfo({
          userId: this.userInfo.userId,
          userInfo: { connectSpeechStatus: 2, audio: true },
        });
        if (res && res.status == 200 && res.data.userId) {
          this.$message({ type: "success", message: "申请连麦请求已发送", });
          // 向主持人发送IM申请连麦的请求
          console.log('申请连麦成功', res.data)
          res.data['toUserId'] = this.roomInfo.masterId;
          let data = {
            data: res.data,
            description: "applyConnectAudio",
            extension: "TRTCControl",
          };
          data.data = JSON.stringify(data.data);
          this.$store.dispatch("setIMFn", { name: "createCustomMessage", data: { data } });
        } else {
          this.$message({ type: "error", message: "连麦请求发送失败", });
        }
      }
    },
    // 连麦模式下,切回观看,声音,视频,投屏,结束互动等
    async connectAudioClick(item, index) {
      // 切回观看,自动断开连麦,和主讲模式
      if (item.name == '切回观看') {
        this.backWatch(item);
      }
      // 停止声音
      if (item.class == 'audio') {
        item.active = !item.active;
        this.$emit("muteAudio", item.active);
      }
      // 停止视频
      if (item.class == 'video') {
        item.active = !item.active;
        this.$emit("muteVideo", item.active);
      }
      // 结束互动
      if (item.name == '结束互动') {
        let res = await UserAPI.updateUserInfo({
          userId: this.userInfo.userId,
          userInfo: { isInteraction: true, video: true, audio: false, connectSpeechStatus: 1, isMasterSpeech: false },
        });
        if (res && res.status == 200 && res.data.userId) {
          this.$message({ type: "success", message: "结束互动成功" });
          console.log(res.data);
          let data = {
            data: res.data,
            description: "updateUser",
            extension: "TRTCControl",
          };
          data.data = JSON.stringify(data.data);
          // 向其他用户广播最新用户信息
          this.$store.dispatch("setIMFn", { name: "createCustomMessage", data: { data } });
          // 修改stote
          this.$store.dispatch("setUserInfo", res.data);
          // 用户重新变为互动用户时,需要取消trtc推流
          this.$store.dispatch("setTRTCFn", { name: "unpublish" });
        } else {
          this.$message({ type: "error", message: "互动参会失败", });
        }
      }
    },
    // 讲者模式
    async lecturerListClick(item, index) {
      // 停止声音
      if (item.class == 'audio') {
        item.active = !item.active;
        this.$emit("muteAudio", item.active);
      }
      // 停止视频
      if (item.class == 'video') {
        item.active = !item.active;
        this.$emit("muteVideo", item.active);
      }
      if (item.name == '申请主讲') {
        // 向主播发送申请主讲请求
        let userInfo = this.userInfo;
        userInfo['toUserId'] = this.roomInfo.masterId;
        let data = {
          data: userInfo,
          description: "applyMasterSpeech",
          extension: "TRTCControl",
        };
        data.data = JSON.stringify(data.data);
        // 向其他用户广播最新用户信息
        this.$store.dispatch("setIMFn", { name: "createCustomMessage", data: { data } });
      }
      if (item.name == '归还主讲') {
        this.backMasterSpeech();
      }
    },
    // 切回观看的方法
    async backWatch(item) {
      console.log("切换到观看模式");
      let res = await UserAPI.updateUserInfo({
        userId: this.userInfo.userId,
        userInfo: { isInteraction: false, connectSpeechStatus: 1, isMasterSpeech: false, video: false, audio: false },
      });
      if (res && res.status == 200 && res.data.userId == this.userInfo.userId) {
        this.$message({ type: "success", message: "已切换观看模式" });
        // 向其他用户广播最新用户信息
        console.log(res.data);
        let data = {
          data: res.data,
          description: "updateUser",
          extension: "TRTCControl",
        };
        data.data = JSON.stringify(data.data);
        this.$store.dispatch("setIMFn", { name: "createCustomMessage", data: { data } });
        // 用户变为观看模式时,需要关闭trtc和白板
        this.$store.dispatch("setUserInfo", res.data);
        // 关闭trtc
        this.$store.dispatch("setTRTCFn", { name: "leaveRoom", });
        // 关闭白板
        this.$store.dispatch("setTEFn", { name: "destroyTE", });
      } else {
        this.$message({ type: "error", message: "切换观看模式失败", });
      }

    },
    // 归还主讲的方法
    backMasterSpeech(item) {

      this.$confirm("确认归还主讲？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        let res = await UserAPI.updateUserInfo({
          userId: this.userInfo.userId,
          userInfo: { isMasterSpeech: false },
        });
        if (res && res.status == 200 && res.data.userId) {
          this.$message({ type: "success", message: "归还主讲成功" });
          let data = {
            data: res.data,
            description: "updateUser",
            extension: "TRTCControl",
          };
          data.data = JSON.stringify(data.data);
          // 向其他用户广播最新用户信息
          this.$store.dispatch("setIMFn", { name: "createCustomMessage", data: { data } });
          // 修改stote
          this.$store.dispatch("setUserInfo", res.data);
        } else {
          this.$message({ type: "success", message: "归还主讲失败" });
        }
      })
    }
  },
};
</script>

<style lang="scss" scoped>
.set_container {
  display: flex;
  justify-content: space-between;
  background: #fff;
  flex: 1;
  padding: 8px 20px;
  box-sizing: border-box;
}
.meet_operate {
  width: 50%;
  .set-list {
    display: flex;
  }
  .set-box {
    display: flex;
    width: 12%;
    flex-direction: column;
    align-items: center;
    justify-content: space-evenly;

    cursor: pointer;
    font-size: 9px;
    font-weight: 400;
    color: rgba(0, 0, 0, 0.85);
    line-height: 13px;
    .icon_box {
      height: 30px;
      display: flex;
      align-items: center;
      position: relative;
    }
    .icon {
      width: 20px;
      height: 20px;
    }
    &.audio {
      .icon {
        height: 22px;
        width: auto;
      }
    }
    &.video {
      .icon {
        height: 15px;
        width: auto;
      }
    }
    &.share {
      .icon {
        height: 20px;
        width: auto;
      }
    }
    &.member {
      .icon {
        height: 19px;
        width: auto;
      }
      .number {
        box-sizing: border-box;
        background: #e94642;
        border-radius: 7px;
        position: absolute;
        padding: 0 5px;
        text-align: center;
        line-height: 15px;
        left: 10px;
        top: -3px;
        z-index: 2;
        color: #ffffff;
      }
    }
    &.layout {
      .icon {
        height: 26px;
        width: auto;
      }
      .play_icon {
        position: absolute;
        width: 15px;
        height: 15px;
        right: -3px;
        top: -3px;
        z-index: 2;
      }
    }
  }
}
.meet_info {
  width: 35%;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  font-size: 18px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
  line-height: 25px;
  .meet_number {
    cursor: pointer;
  }
  .meet_number,
  .meet_time {
    display: flex;
    align-items: center;
  }
  .line {
    width: 1px;
    height: 20px;
    background: rgba(0, 0, 0, 0.15);
    margin-left: 16px;
    margin-right: 20px;
  }
  img {
    width: 20px;
    height: 20px;
    margin-right: 8px;
  }
  .button {
    box-sizing: border-box;
    border-radius: 2px;
    height: 44px;
    line-height: 42px;
    padding: 0 11px;
    display: flex;
    justify-content: space-around;
    text-align: center;
    font-size: 18px;
    font-weight: 500;
    cursor: pointer;
    margin-left: 20px;
    &.meet_end {
      border: 2px solid #e94642;
      color: #e94642;
    }
    &.meet_start {
      border: 2px solid #475aa7;
      color: #475aa7;
    }
  }
}
</style>